﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using PD;

public sealed class UIMa : Singleton<UIMa>
{
    private UIMa() { }

    private GameObject mUIRoot;
    private Dictionary<EUI, string> mUIInfoDic = new Dictionary<EUI, string>();
    private Dictionary<EUI, BaseUI> mUIDic = new Dictionary<EUI, BaseUI>();

    public GameObject UIRoot
    {
        get
        {
            return mUIRoot;
        }

        set
        {
            mUIRoot = value;
        }
    }

    public void Init()
    {
        mUIInfoDic.Add(EUI.Login, "UI/UILogin");
    }

    public BaseUI ShowUI(EUI type, object arg = null)
    {
        if (!mUIInfoDic.ContainsKey(type))
            return null;

        BaseUI ui = CreateUI(type, arg);//创建UI
        if (null == ui)
            return null;

        if (!ui.Init())
        {
            Debug.LogError("UI init failed : " + type);
            GameObject.Destroy(ui.gameObject);
            return null;
        }

        mUIDic.Add(type, ui);
        ui.transform.SetParent(UIRoot.transform, false);
        return ui;
    }

    private BaseUI CreateUI(EUI type, object arg)
    {
        Object g = null;

        if (mUIInfoDic.ContainsKey(type))
        {
            g = Resources.Load(mUIInfoDic[type]);
        }
        if (null == g)
        {
            Debug.LogError(mUIInfoDic[type] + " is not exit");
            return null;
        }
        GameObject go = GameObject.Instantiate(g) as GameObject;

        BaseUI ui = go.GetComponent<BaseUI>();
        if (null == ui)
        {
            Debug.LogError("没有UI_Base " + mUIInfoDic[type]);
            GameObject.Destroy(go);
            Resources.UnloadAsset(g);
            return null;
        }

        return ui;
    }

    public void CloseUI(EUI type)
    {

    }

    public T GetUIBase<T>(EUI type) where T : BaseUI
    {
        if (mUIDic.ContainsKey(type))
        {
            return mUIDic[type] as T;
        }
        return null;
    }

}
